package gosnoopers.fr;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import lazy_listview.ImageLoader;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import common.PickImage;
import components.MultipartUtility;

public class InscriptionAvatarActivity extends Activity {

	private Bitmap bitmap;
	private ImageView mImgContent;
	private ProgressBar mProBarUploading;
	public static String logo = "http://gosnoopers.com/uploads/inscriptions/";
	public ImageLoader imageLoader; 
	
	//*********************CREATE************************
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inscription_avatar);
						
		mImgContent = (ImageView) findViewById(R.id.logo);
		
		imageLoader=new ImageLoader(getApplicationContext());
		imageLoader.DisplayImage(logo, mImgContent);
		mProBarUploading = (ProgressBar) findViewById(R.id.probar_uploading);
		Button btn_change = (Button) findViewById(R.id.btn_change);
		btn_change.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				PickImage.pickImage(InscriptionAvatarActivity.this);
			}
		});
	}
	
	
	/**
	 * onActivityResult. Receiver image from you choosed
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == PickImage.REQUEST_CODE_PICK_IMAGE){
			if((resultCode == RESULT_OK) && (data != null)) {
				bitmap = null;
				bitmap = PickImage.getPath(data.getData(), InscriptionAvatarActivity.this);
				mImgContent.setImageBitmap(bitmap);
				mImgContent.setVisibility(View.VISIBLE);
				
				new PostPhotoToServer(MainActivity.userId, bitmap).execute();
			}
		}
	}
	
	/**
	 * Class asynctask post photo to server
	 */
	private class PostPhotoToServer extends AsyncTask<Void, Void, Boolean> {
		
		private Bitmap mBitmap;
		private String id;
		public  String messagePostPhoto = "";
		
		public PostPhotoToServer(String id, Bitmap bitmap) {
			this.id = id;
			this.mBitmap = bitmap;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProBarUploading.setVisibility(View.VISIBLE);
		}
		@Override
		protected Boolean doInBackground(Void... params) {
			return ( execuseUploadPhoto(id, mBitmap) );
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			// error is false -> result is true
			if(result == false) {
				mProBarUploading.setVisibility(View.GONE);	
				Toast.makeText(getApplicationContext(),
						"Upload image ok!", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(getApplicationContext(),
						messagePostPhoto, Toast.LENGTH_SHORT).show();
			}
		}
		
		
		/**
		 * @author TienLQ
		 *  Method upload photo
		 */
		private boolean execuseUploadPhoto (String id, Bitmap bm){
			String uRLPost = "http://gosnoopers.com/inscriptions/app/uploadImage?uuid="+id;
			try{
					File file = getFilePath(bm);
					
					MultipartUtility multipart = new MultipartUtility(uRLPost,"UTF-8");
					
		            multipart.addFormField("id", id);
		            multipart.addFilePart("image", file);
		            
		            List<String> response = multipart.finish();
		            
		           System.out.println("SERVER REPLIED:");
		             
		            for (String line : response) {
		                System.out.println(line);
		                JSONObject jsonDataResult= new JSONObject(line);
		                Log.d("POST PHOTO ", "DEBUG: "+jsonDataResult);
		                messagePostPhoto = jsonDataResult.getString("message");
		                return jsonDataResult.getBoolean("error");
		            }
			} catch(Exception e) {
				e.printStackTrace();
			}
			return false;
		}
		
		/**
		 * @author TienLQ
		 * Convert from bitmap to File for upload
		 * 
		 */
		private File getFilePath(Bitmap bm) {
			String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
			
			Log.i("ImageUtil", "extStorageDirectory: " + extStorageDirectory);
			OutputStream outStream = null;
			File file = new File(extStorageDirectory, "c12xcxcxccvcx" + "." + "JPEG");
			try {
				outStream = new FileOutputStream(file);
				bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
				try {
					outStream.flush();
					outStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return file;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			return null;
		}
		
	}
	
}
